package org.darkforest.common.services.impl;

import java.util.HashMap;
import java.util.Map;

import org.darkforest.common.logger.Logger;
import org.darkforest.common.mail.MailUtil;
import org.darkforest.common.services.MessageAndNoticeService;
import org.darkforest.common.services.MobileMsgService;
import org.darkforest.common.services.SimpleRedisService;
import org.darkforest.common.services.SmsService;
import org.darkforest.common.util.SmsSendUtil;
import org.darkforest.common.util.SystemConstant;
import org.darkforest.dao.mapper.MemberMsgTplMapper;
import org.darkforest.model.MemberMsgTpl;
import org.darkforest.vo.SmsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by valentina on 15/3/30.
 */
@Service
public class SmsServiceImpl implements SmsService{

    @Autowired
    private SimpleRedisService redisOper;
    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;
    @Autowired
    private MobileMsgService mobileMsgService;
    @Autowired
    private MessageAndNoticeService messageAndNoticeService;

    /**
     * 将验证码存储于redis，并发送短信
     * @param phoneNum
     * @param validMintes
     * @return
     */
    public SmsResult sendCaptcha(String phoneNum, Integer validMintes) {
        SmsResult smsResult = new SmsResult();
        try{
            //计算验证码失效时间：现有时间+SMS_TEMPLETE_CAPTCHA_TIME
            //如redis里的验证码未过期，首选使用redis中的验证码
//            String captcha = redisOper.getByKey(phoneNum);
//            if(captcha==null){
            Integer random = (int)(Math.random() * 10000);
            // String captcha = random.toString();
            String captcha = String.format("%04d", random);
            Long validSec = new Long(validMintes * 60);
            redisOper.setValueInTime(phoneNum,captcha,validSec);            //存于redis中的数据超过有效时间即失效
//            }
            Logger.debug(SmsServiceImpl.class,"发送短信校验码，phoneNum："+phoneNum+",captcha:"+captcha);
            //发送手机短信
            MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("authenticate");
            Map<String, Object> smsMap = new HashMap<String, Object>();
            smsMap.put("moblieNumber", phoneNum);
            // 【央联E家】尊敬的用户您好，您的验证码为：{1}，请于{2}分钟内正确输入，工作人员不会向您索取，请勿泄露。
            String[] params = new String[2];
            params[0] = captcha.toString();
            params[1] = 5 + "";
            smsMap.put("params", params);

            messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);

        }catch (Exception e){
            e.printStackTrace();
            smsResult.setSendStatus(false);
            Logger.error(SmsServiceImpl.class,e.getLocalizedMessage());
        }finally {
            return smsResult;
        }
    }

    /**
     * 验证短信验证码，并清除redis中的缓存数据
     * @return
     */
    public boolean verfiyCaptcha(String channel,String captcha) {
        String captcha_inredis = redisOper.getByKey(channel);
        if(captcha==null||captcha.isEmpty()){
            return false;
        }
        if(!captcha.equals(captcha_inredis)){
            return false;
        }
        return true;
    }

    public String contextRepalce(String context,String []str){
        for (int i=0;i<str.length;i++){
            context = context.replace("{"+(i+1)+"}",str[i]);
        }
        return context;
    };

    /****
     * 发送礼品码
     * @return
     */
    @Override
    public boolean sendGiftCode(String phoneNum,String senderName,String giftCode) {
        boolean res = true;
        try{
            MemberMsgTpl memberMsgTpl=memberMsgTplMapper.selectByPrimaryKey("gift_code");
            if(memberMsgTpl != null && memberMsgTpl.getMmtShortId()!=0&&memberMsgTpl.getMmtShortContent()!=null){
                String[] str = new String[2];
                str[0] =senderName;
                str[1] =giftCode+"";
                mobileMsgService.sendMobileMsg(phoneNum,contextRepalce(memberMsgTpl.getMmtShortContent(),str));
            }
        }catch (Exception e){
            e.printStackTrace();
            res = false;
        }finally {
            return res;
        }
    }

    /***
     * 发送邮件code
     * @param email
     * @param seconds
     * @throws Exception
     */
    @Override
    public void sendMailCode(String email, Integer seconds) throws Exception{
//        String captcha = redisOper.getByKey(email);
//        if(captcha==null){
        Integer random = (int)(Math.random()*10000);
        //String captcha = random.toString();
        String captcha = String.format("%04d", random);
        Long validSec = new Long(seconds*60);
        redisOper.setValueInTime(email, captcha, validSec);            //存于redis中的数据超过有效时间即失效
//        }
//        String subject, String content, String[] receivers,
//                String attachmentFilename[], File attach[], boolean attachAsMIME

        Logger.debug(SmsServiceImpl.class,"发送邮箱校验码，email："+email+",captcha:"+captcha);
        String[] receivers = {email};
        if ("465".equals(SystemConstant.PORT.trim())) {
            MailUtil.sendMailBySSL("Mall verification code", captcha, SystemConstant.USERNAME.trim(), receivers);
        } else {
            // 25
            MailUtil.sendMail("Mall verification code", captcha, receivers,null,null,true);
        }
    }
}
